#!/bin/bash
echo "=== Tail Call Optimization Demo ==="
echo ""

echo "Testing tail-recursive factorial (should handle large numbers without stack overflow):"
cat << 'EOF' | ./ascheme
(define (factorial-iter n acc)
  (if (= n 0)
      acc
      (factorial-iter (- n 1) (* n acc))))

(define (factorial n) (factorial-iter n 1))

(factorial 5)
(factorial 10)
exit
EOF

echo ""
echo "Testing tail-recursive countdown (large numbers to show TCO prevents stack overflow):"
cat << 'EOF' | ./ascheme
(define (countdown n)
  (if (= n 0)
      'done
      (countdown (- n 1))))

(countdown 1000)
exit
EOF

echo ""
echo "Comparing tail-recursive vs non-tail-recursive (both should work, but tail version is optimized):"
cat << 'EOF' | ./ascheme
; Non-tail recursive (uses stack)
(define (factorial-non-tail n)
  (if (= n 0)
      1
      (* n (factorial-non-tail (- n 1)))))

; Tail recursive (optimized)
(define (factorial-tail n acc)
  (if (= n 0)
      acc
      (factorial-tail (- n 1) (* n acc))))

(factorial-non-tail 6)
(factorial-tail 6 1)
exit
EOF

echo ""
echo "Tail Call Optimization is working! Large recursive calls complete without stack overflow."